package com.monolithiot.sso.common.util;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 2018/11/19 Create by 郭文梁
 * UploadFileUtil
 * 上传文件工具类
 *
 * @author 郭文梁
 * @date 2018/11/19
 */
public class UploadFileUtil {
    /**
     * 文件定界符
     */
    private static final String DELIMITER_DOT = ".";

    /**
     * 生成随机UUID文件名
     *
     * @param file 上传的文件
     * @return 文件名
     */
    public static String randomUUIDFilename(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (filename == null) {
            filename = "";
        }
        String uuid = IdentityUtil.randomUUID();
        return uuid + getSuffix(filename);
    }

    /**
     * 获取文件后缀名
     *
     * @param filename 文件名
     * @return 后缀名，无后缀时返回空字符串
     */
    public static String getSuffix(String filename) {
        if (filename.contains(DELIMITER_DOT)) {
            int dotIndex = filename.lastIndexOf(DELIMITER_DOT);
            return filename.substring(dotIndex);
        } else {
            return "";
        }
    }

    /**
     * 将上传的文件复制（移动）到指定路径
     *
     * @param file 文件
     * @param path 路径
     * @return 文件名
     * @throws IOException IO异常
     */
    public static String copyTmpFileTo(MultipartFile file, String path) throws IOException {
        File pathFile = new File(path);
        if (!pathFile.exists() || !pathFile.isDirectory()) {
            if (!pathFile.mkdirs()) {
                throw new IOException("Could not create directory: " + path);
            }
        }
        String filename = randomUUIDFilename(file);
        File target = new File(pathFile, filename);
        file.transferTo(target);
        return filename;
    }

    /**
     * 将上传的文件复制（移动）到指定路径
     *
     * @param files 文件数组
     * @param path  路径
     * @return 文件名数组
     * @throws IOException IO异常
     */
    public static String[] copyTmpFileTo(MultipartFile[] files, String path) throws IOException {
        if (files == null) {
            return null;
        }
        List<MultipartFile> fileList = Arrays.asList(files);
        List<String> filenameList = copyTmpFileTo(fileList, path);
        return filenameList.toArray(new String[fileList.size()]);
    }

    /**
     * 将上传的文件复制（移动）到指定路径
     *
     * @param fileList 文件列表
     * @param path     路径
     * @return 文件名列表
     * @throws IOException IO异常
     */
    @NotNull
    public static List<String> copyTmpFileTo(List<MultipartFile> fileList, String path) throws IOException {
        List<String> names = new ArrayList<>();
        for (MultipartFile file : fileList) {
            String name = copyTmpFileTo(file, path);
            names.add(name);
        }
        return names;
    }
}
